<template>
  <div class="head-container">
    <!-- 头部信息 -->
    <div class="head-container-header">
      <div class="head-container-header-input">
        <el-input v-model="filterText" :placeholder="placeholder" clearable prefix-icon="search"/>
      </div>
      <div v-if="showExpand" class="head-container-header-dropdown">
        <el-dropdown :hide-on-click="false">
          <el-icon style="transform: rotate(90deg)">
            <MoreFilled/>
          </el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>
                <el-button :icon="expand ? 'expand' : 'fold'" link type="primary" @click="handleToggleExpansionAll">
                  {{ expand ? '折叠' : '展开' }}
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 树形结构 -->
    <el-tree ref="treeRef" :data="treeData"
             :expand-on-click-node="false"
             v-loading="loading"
             :node-key="treeKey"
             :props="treeProps"
             class="mt-3"
             default-expand-all
             highlight-current
             @node-click="handleNodeClick"
             :filter-node-method="handleTreeFilterNode"
             :style="{'min-height': '36.2rem', overflow:'auto'}">
      <template v-if="$slots.default" #default="{ node, data }">
        <slot :data="data" :node="node"></slot>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { MoreFilled } from '@element-plus/icons-vue';
import { ElTree } from 'element-plus';

defineOptions({name: 'tree-data'});

const props = defineProps({
  treeData: {
    type: Array,
    default: () => []
  },
  treeKey: {
    type: String,
    default: 'id'
  },
  treeProps: {
    type: Object,
    default() {
      return {label: 'name', children: 'children'}
    }
  },
  loading: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: '请输入关键词',
  },
  showExpand: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['search', 'nodeClick']);
const filterText = ref(''); // 查询关键字
const expand = ref(true); // 是否展开所有节点
const treeRef = ref<InstanceType<typeof ElTree>>();

/**
 * 监听过滤字符串。
 */
watch(filterText, (val) => {
  treeRef.value?.filter(val)
});

/**
 * 处理树形结构搜索
 */
const handleTreeFilterNode = (value: string, data: any) => {
  if (!value) return true
  // 这个地方需要注意
  return data.name.includes(value)
};

/**
 * 切换所有节点的展开/收起状态。
 */
const handleToggleExpansionAll = () => {
  expand.value = !expand.value;
}

/**
 * 点击树形结构节点触发的事件。
 */
const handleNodeClick = (item: any) => {
  emit('nodeClick', item);
};
</script>

<style lang="scss" scoped>
.head-container {
  &-header {
    display: flex;
    align-items: center;

    &-input {
      width: 90%;
    }

    &-dropdown {
      flex: 1;
      margin-left: 5%;
    }
  }
}
</style>
